<?php

namespace App\Service\Feishu\Event;

use App\Enums\Feishu\EventEnum;
use App\Models\Feishu\FeishuEventLogsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class EventService
{
    private string $eventType;

    private string $schema;

    private string $eventId;

    private string $token;

    private string $eventCreateTime;

    private string $tenantKey;

    private string $appId;

    private array $eventData;

    private array $allParams;

    public function __construct()
    {
    }

    public function analyseRequest(Request $request)
    {
        $this->allParams = $request->all();
        $this->schema    = $request->get('schema', '');
        $requestHeader   = $request->get('header', []);

        $this->eventType       = $requestHeader['event_type'] ?? '';
        $this->eventId         = $requestHeader['event_id'] ?? '';
        $this->token           = $requestHeader['token'] ?? '';
        $this->eventCreateTime = $requestHeader['create_time'] ?? '';
        $this->tenantKey       = $requestHeader['tenant_key'] ?? '';
        $this->appId           = $requestHeader['app_id'] ?? '';

        $this->eventData = $request->get('event', []);
    }

    public function handle(): array
    {
        $this->recordLog();
        $this->saveLog();

        if(!empty($this->allParams['challenge'])){
            return self::urlVerification();
        }

        if (empty($this->schema) || $this->schema == '1.0') {
            return self::handleV1();
        } else {
            return self::handleV2();
        }
    }

    private function handleV1(): array
    {
        return [];
    }

    private function handleV2(): array
    {
        $className = $this->getClass();
        if (class_exists($className)) {
            $class = new $className($this->eventData);
            $class->handle();
        } else {
            $this->recordError('event type 对应的类不存在');
        }
        return [];
    }

    private function urlVerification(): array
    {
        return ['challenge' => $this->allParams['challenge']];
    }

    private function saveLog()
    {
        FeishuEventLogsModel::query()->create($this->getFullParams());
    }

    private function getFullParams(): array
    {
        return [
            'schema'          => $this->schema,
            'eventType'       => $this->eventType,
            'eventId'         => $this->eventId,
            'token'           => $this->token,
            'eventCreateTime' => $this->eventCreateTime,
            'tenantKey'       => $this->tenantKey,
            'appId'           => $this->appId,
            'eventData'       => $this->eventData,
        ];
    }

    public function getAllParams(): array
    {
        return $this->allParams;
    }

    private function getClass(): string
    {
        $class = explode('.', $this->eventType);
        foreach ($class as &$value) {
            $value = underscoreToCamelCase($value, true);
        }
        return __NAMESPACE__ . '\\' . implode('\\', $class);
    }

    private function recordLog()
    {
        // 记录日志
        Log::info('tiger_event_notify_logs', $this->getAllParams());
    }

    private function recordError(string $msg = '')
    {
        Log::error('tiger_event_notify_error_logs', ['msg' => $msg] + $this->getFullParams());
    }
}